package coom;

import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.net.ConnectException;
import java.net.UnknownHostException;

import base.BaseResp;
import event.LoginEvent;
import event.NetErrorEvent;
import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;
import util.ToastUtils;

/**
 * Created by chenjian
 */
public abstract class BaseSubscribe<T> extends Subscriber<T> {
    private String track;

    public String getTrack() {
        return track;
    }

    public void setTrack(String track) {
        this.track = track;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String errorMsg = e.getMessage();
        if (TextUtils.isEmpty(errorMsg)) {
            errorMsg = "服务器连接失败,请稍后再试";
        }
        NetErrorEvent errorEvent = new NetErrorEvent();
        errorEvent.setTrack(track != null ? track : "");
        if (e instanceof UnknownHostException || e instanceof ConnectException) {
            errorMsg = "无法连接服务器,请检查手机网络";
            errorEvent.setLevel(0);
        } else if (e instanceof HttpException) {
//            HttpException httpException= (HttpException) e;
//            switch (httpException.code()){}
            errorEvent.setLevel(0);
        } else {
            errorEvent.setLevel(1);
        }
        EventBus.getDefault().post(errorEvent);
        if("HTTP 401 Unauthorized".equals(errorMsg)){
//            ToastUtils.shortToast("登录状态失效，请重新登录");
        }else{
            ToastUtils.shortToast(errorMsg);
        }

    }

    @Override
    public void onNext(T t) {
        BaseResp resp = (BaseResp) t;
        switch (resp.getResult()) {
            case 00000000:
                onSuccess(resp.getData());
                break;
            case 90000001:
                onFailure(resp.getData());
                ToastUtils.shortToast(resp.getMsg() + "");
                break;
            case 10000010:
                onFailure(resp.getData());
                ToastUtils.shortToast(resp.getMsg() + "");
                break;
            case 401:
                onFailure(resp.getData());
                ToastUtils.shortToast("登录状态失效，请重新登录");
                EventBus.getDefault().post(new LoginEvent());
                break;
            case 10000002:
                onFailure(resp.getData());
                ToastUtils.shortToast(resp.getMsg() + "");
                break;
            default:
                ToastUtils.shortToast(resp.getMsg() + "");
                onFailure(resp.getData());
                break;
        }
    }

    public abstract void onSuccess(Object obj);

    public abstract void onFailure(Object obj);
}
